package io.yichen.usbflutter.usb.driver;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UsbEngine {

    private static final String TAG = "UsbEngine";

    private List<UsbItem> listItems = new ArrayList<>();
    private Map<Integer, UsbConnector> connectorMap = new HashMap<>();

    public void destroy() {
        disconnectAll();
    }

    /**
     * 连接usb设备
     *
     * @param id       设备id
     * @param baudRate 波特率
     * @param listener 数据监听
     */
    public UsbResult connect(Context context,int id, int baudRate, SerialInputOutputManager.Listener listener) {
        if (listItems.isEmpty()) {
            return UsbResult.err().msg("无设备可链接");
        }
        for (UsbItem item : listItems) {
            if (item.device.getDeviceId() == id) {
                connectorMap.remove(id);
                UsbConnector connector = new UsbConnector();
                UsbResult result = connector.connect(context, item, baudRate, listener);
                if (result.code != 0) {
                    return result;
                }
                connectorMap.put(id, connector);
                return result;
            }
        }
        return UsbResult.err().msg("未找到设备");
    }


    /**
     * 刷新usb设备列表
     *
     * @return
     */
    public List<UsbItem> refreshList(Context context) {
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        UsbSerialProber usbDefaultProber = UsbSerialProber.getDefaultProber();
        UsbSerialProber usbCustomProber = CustomProber.getCustomProber();
        Map<String, UsbDevice> devices = usbManager.getDeviceList();
        listItems.clear();

        for (UsbDevice device : devices.values()) {
            UsbSerialDriver driver = usbDefaultProber.probeDevice(device);
            if (driver == null) {
                driver = usbCustomProber.probeDevice(device);
            }
            if (driver != null) {
                for (int port = 0; port < driver.getPorts().size(); port++)
                    listItems.add(new UsbItem(device, port, driver));
            } else {
                listItems.add(new UsbItem(device, 0, null));
            }
        }
        Log.d(TAG, String.format("找到了%s个设备", devices.size()));
        return listItems;
    }

    /**
     * @param deviceId
     */
    public void disconnect(Integer deviceId) {
        UsbConnector connector = connectorMap.remove(deviceId);
        if (connector != null) {
            connector.disconnect();
        }
    }

    public void disconnectAll() {
        for (Map.Entry<Integer, UsbConnector> entry : connectorMap.entrySet()) {
            entry.getValue().disconnect();
        }
        connectorMap.clear();
    }
}
